package gemini.pollux.ui.client.page.content.product.product.edit;

import gemini.basic.model.AbstractDomain;
import gemini.basic.model.Product;
import gemini.basic.model.ProductDetail;
import gemini.basic.model.ProductType;
import gemini.pollux.ui.client.mvp.gin.PolluxGinjector;
import gemini.pollux.ui.client.page.RootEvent;
import gemini.pollux.ui.client.utils.GuiUtils;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class ProductEditView extends Composite implements
		ProductEditPresenter.Display {

	@UiTemplate("ProductEditView.ui.xml")
	interface MyUiBinder extends UiBinder<Panel, ProductEditView> {
	}

	private static final MyUiBinder binder = GWT.create(MyUiBinder.class);

	public ProductEditView() {
		initWidget(binder.createAndBindUi(this));
	}

	@UiField
	HTML htmTitle;

	@UiField
	HTML htmInformation;

	@UiField
	TextBox tbxName;

	@UiField
	TextBox tbxCode;
	
	@UiField
	TextBox tbxImage;
	
	@UiField
	TextBox tbxPoint;

	@UiField
	TextArea tarContent;
	
	@UiField
	TextArea tarUserGuide;
	
	@UiField
	TextArea tarOverview;
	
	@UiField
	TextArea tarKeyBenefit;
	
	@UiField
	TextArea tarFastFacts;

	@UiField
	ListBox lbxProductType;

	@UiField
	Button btnSubmit;

	@UiField
	Button btnBack;

	@UiField
	Button btnReset;
	
	@UiField
	FormPanel formPanel;
	
	@UiField
	Button btnUpload;
	
	@UiHandler("btnUpload")
	void onUpload(ClickEvent event) {
		formPanel.submit();
	}

	@UiHandler("btnReset")
	void resetFields(ClickEvent event) {
		loadForm();
	}

	@Override
	public void initCustom() {

		tarContent.setSize("300px", "100px");
		tarFastFacts.setSize("300px", "100px");
		tarKeyBenefit.setSize("300px", "100px");
		tarOverview.setSize("300px", "100px");
		tarUserGuide.setSize("300px", "100px");
		
		tbxName.setWidth("300px");
		tbxPoint.setWidth("300px");
		tbxCode.setWidth("300px");
		tbxImage.setWidth("300px");
		lbxProductType.setWidth("300px");
		
		tbxName.setMaxLength(30);
		tbxImage.setMaxLength(50);
		tbxCode.setMaxLength(5);
		tbxPoint.setMaxLength(3);

		if (product == null) {
			htmTitle.setHTML("<h3>New Product</h3>");
			htmInformation
					.setHTML("Fill bellow information to create new product");
		} else {
			htmTitle.setHTML("<h3>Update Product</h3>");
			htmInformation.setHTML("Update bellow information to update product");
		}

		loadForm();
		
		initFormPanel();
	}

	@Override
	public Widget asWidget() {
		return this;
	}

	private Product product;

	private List<ProductType> productTypes;

	@Override
	public HasClickHandlers getBackClickHandlers() {
		return btnBack;
	}

	@Override
	public HasClickHandlers getSubmitClickHandlers() {
		return btnSubmit;
	}

	@Override
	public void setProduct(Product product) {
		this.product = product;
	}

	public void loadForm() {
		if (this.product == null) {
			tbxName.setValue("");
			tbxPoint.setValue("");
			tbxCode.setValue("");
			tbxImage.setValue("images/product/no_image.png");
			tarContent.setValue("");
			tarFastFacts.setValue("");
			tarKeyBenefit.setValue("");
			tarOverview.setValue("");
			tarUserGuide.setValue("");
		} else {
			tbxName.setValue(this.product.getName());
			tbxCode.setValue(this.product.getCode());
			tbxImage.setValue(this.product.getImageUrl());
			tbxPoint.setValue(String.valueOf(this.product.getVolumePoint()));
			
			tarContent.setValue(this.product.getProductDetail().getContent());
			tarFastFacts.setValue(this.product.getProductDetail().getFastFacts());
			tarKeyBenefit.setValue(this.product.getProductDetail().getKeyBenefit());
			tarOverview.setValue(this.product.getProductDetail().getOverview());
			tarUserGuide.setValue(this.product.getProductDetail().getUserGuide());
		}

		lbxProductType.clear();
		if (productTypes != null) {
			for (ProductType prT : productTypes) {
					lbxProductType.addItem(prT.getName(),
							String.valueOf(prT.getId()));
			}
		}
	}

	@Override
	public Product getProduct() {
		if (product == null) {
			product = new Product();
			product.setId(AbstractDomain.TRANSIENT_ENTITY_ID);
			
			product.setProductDetail(new ProductDetail());
		}
		
		String content = tarContent.getValue();

		if(content != null && content.length() > 300){
			content.substring(0, 299);
		}
		
		product.getProductDetail().setContent(content);
		
		String keyBenefit = tarKeyBenefit.getValue();

		if(keyBenefit != null && keyBenefit.length() > 300){
			keyBenefit.substring(0, 299);
		}
		
		product.getProductDetail().setKeyBenefit(keyBenefit);
		
		String fastFacts = tarFastFacts.getValue();

		if(fastFacts != null && fastFacts.length() > 300){
			fastFacts.substring(0, 299);
		}
		
		product.getProductDetail().setFastFacts(fastFacts);
		
		String overview = tarOverview.getValue();

		if(overview != null && overview.length() > 300){
			overview.substring(0, 299);
		}
		
		product.getProductDetail().setOverview(overview);
		
		String useGuide = tarUserGuide.getValue();

		if(useGuide != null && useGuide.length() > 300){
			useGuide.substring(0, 299);
		}
		
		product.getProductDetail().setUserGuide(useGuide);
		
		product.setName(tbxName.getValue());
		product.setCode(tbxCode.getValue());
		product.setVolumePoint(Short.valueOf(tbxPoint.getValue()));
		product.setUnit("canister");
		product.setImageUrl(tbxImage.getValue());

		if (lbxProductType.getItemCount() > 0) {
			String productTypeId = lbxProductType.getValue(lbxProductType
					.getSelectedIndex());

			if (productTypeId != null) {
				ProductType productType = new ProductType();
				productType.setId(Integer.parseInt(productTypeId));
				product.setProductType(productType);
			}
		}

		return product;
	}
	
	private void initFormPanel() {
		formPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
		formPanel.setMethod(FormPanel.METHOD_POST);
		
		FileUpload fileUpload = new FileUpload();
		
		VerticalPanel holder = new VerticalPanel();

		fileUpload.setName("upload");
		holder.add(fileUpload);
		
		formPanel.add(holder);
		
		formPanel.addSubmitHandler(new FormPanel.SubmitHandler() {
			public void onSubmit(SubmitEvent event) {
				PolluxGinjector.INSTANCE.getEventBus().fireEvent(new RootEvent(
						RootEvent.ForwardType.MASK));
				
				//formPanel.setAction("http://localhost:8080/gemini-castor-web-0.2/castor/fileread");
				formPanel.setAction(GWT.getModuleBaseURL() + "fileread");
			}
		});

		formPanel.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
			public void onSubmitComplete(SubmitCompleteEvent event) {
				if(event.getResults() != null){
					String returnStr = event.getResults().toString();
					returnStr = returnStr.substring(5, returnStr.length() - 6);
					
					if(returnStr.startsWith("images")){
						tbxImage.setValue(returnStr);
					} else {
						GuiUtils.alert(returnStr);
					}
				} else {
					GuiUtils.alert("Error when uploading image! Please try again or using default image!");
				}
				
				PolluxGinjector.INSTANCE.getEventBus().fireEvent(new RootEvent(
						RootEvent.ForwardType.UN_MASK));
			}
		});
	}
	
	@Override
	public FormPanel getFormPanel(){
		return formPanel;
	}

	@Override
	public void setProductTypes(List<ProductType> productTypes) {
		this.productTypes = productTypes;
	}
}
